package cn.chinaflame.pagodas.utils;

import com.google.gson.Gson;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.apache.xerces.parsers.SAXParser;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 测试调用一些meeting第三方接口
 *
 * @author
 */
public class HttpPostUtil {

    /**
     * @param args
     */
    private static final Logger LOG = LoggerFactory.getLogger(HttpPostUtil.class);

    public static void main (String[] args) {
        LOG.info("111");
        Gson gson = new Gson();
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("inputCharset", "1");//默认填 1；1 代表 UTF-8、2 代表 GBK、3 代表GB2312;
        params.put("returnUrl", ""); 	//佛龛无用
        //佛龛
        params.put("notifyUrl", "http:www.baidu.com");
        params.put("version", "v1.0");
        params.put("language", "1");
        params.put("orderNo", "1141172956");	//订单号
        params.put("orderCurrency", "0");		//订单金额币种 类型	默认填 0
        params.put("orderDatetime", DateTimes.nowDateTime());
        params.put("issuerId", "");			//佛龛无用但必填
        params.put("sign", "");				//佛龛无用
        params.put("orderAmount", "1");
        params.put("acct", "ob5hB0n0z_vqRvpBTyLKaIauBzcE");	//用户ID  ，微信为openid，支付宝为user_id
        params.put("sub_merchantId","20180201091200");
        params.put("merchantId", "1111111111111111");	//商户号
        params.put("tradeType", "PAY");
        params.put("payWay", "weixinpay");
        params.put("tradeChannel", "wechat");//可取的值：online线上；offline 线下；wechat 线上微信公众号
        params.put("tradeMethod", "wechatjs");	//可取的值：fastbank银行卡快捷; ebank网银支付;wxqrcode微信二维码;
        //aliqrcode支付宝二维码;wechatjs微信js支付，alipayjs支付宝js支付，generalpos普通pos刷卡;inteligencepos智能pos刷卡，
//		String url = "http://tupay.china-flame.cn/gateway/trade/pay";
        String receive = HttpPostUtil.doPost("http://47.100.46.40:18004/gateway/trade/pay", gson.toJson(params));
        LOG.info("receive:"+receive);
    }

    /**
     * 发送xml数据请求到server端
     *
     * @param url  xml请求数据地址
     * @param data 发送的数据流
     * @return null发送失败，否则返回响应内容
     */
    public static String doPost(String url, String data) {
        //创建httpclient工具对象   
        HttpClient client = new HttpClient();
        //创建post请求方法   
        PostMethod myPost = new PostMethod(url);
        //设置请求超时时间   
        client.setConnectionTimeout(5 * 60 * 1000);//5分钟
        String responseString = null;
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = null;

        try {
            myPost.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));
            int statusCode = client.executeMethod(myPost);
            if (statusCode == HttpStatus.SC_OK) {
                bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
                byte[] bytes = new byte[1024];
                bos = new ByteArrayOutputStream();
                int count = 0;
                while ((count = bis.read(bytes)) != -1) {
                    bos.write(bytes, 0, count);
                }
                byte[] strByte = bos.toByteArray();
                responseString = new String(strByte, 0, strByte.length, "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException ex) {
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException ex) {
                }
            }
        }
        if (myPost != null) {
            myPost.releaseConnection();
        }
        return responseString;
    }

    public static String doPost1(String url, String data) {
        LOG.info("远程post请求url:{},data:{}", url, data);
        //创建httpclient工具对象   
        HttpClient client = new HttpClient();
        //创建post请求方法   
        PostMethod myPost = new PostMethod(url);
        //设置请求超时时间   
//        client.setConnectionTimeout(5 * 60 * 1000);//5分钟
//        client.setConnectionTimeout(1 * 60 * 1000);//1分钟
        client.setConnectionTimeout(1 * 30 * 1000);//30秒
        String responseString = null;
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = null;
        try {
            myPost.setRequestEntity(new StringRequestEntity(data, "application/x-www-form-urlencoded", "UTF-8"));
            int statusCode = client.executeMethod(myPost);
            LOG.info("远程post请求返回码及返回信息statusCode:{},statusText:{}", statusCode, myPost.getStatusText());
            if (statusCode == HttpStatus.SC_OK) {
                bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
                byte[] bytes = new byte[1024];
                bos = new ByteArrayOutputStream();
                int count = 0;
                while ((count = bis.read(bytes)) != -1) {
                    bos.write(bytes, 0, count);
                }
                byte[] strByte = bos.toByteArray();
                responseString = new String(strByte, 0, strByte.length, "utf-8");
                LOG.info(responseString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException ex) {
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException ex) {
                }
            }
        }
        if (myPost != null) {
            myPost.releaseConnection();
        }

        return responseString;
    }


    public static String sendPost(String url, String reqStr) {
        LOG.info("json请求url:{},reqStr:{}", url, reqStr);
        String result = "";
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(connection.getOutputStream());
            // 发送请求参数
            out.print(reqStr);
            // flush输出流的缓冲
            out.flush();
            // 建立实际的连接
            connection.connect();
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), Charset.forName("UTF-8")));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            throw new RuntimeException("REST请求异常", e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                throw new RuntimeException("REST请求异常", e2);
            }
        }
        return result;
    }

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlName = url + (StringUtils.isNotBlank(param) ? "?" + param : "");
            URL realUrl = new URL(urlName);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            // 建立实际的连接
            conn.connect();
            // 获取所有响应头字段
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                //    result += "/n" + line;
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取xml body
     * @param xml
     * @return
     */
    public static String getBody(String xml) {
    	LOG.info("xml={}",xml);
        SAXBuilder builder = new SAXBuilder();
        String value = "";
        try {
        	if(StringUtils.isNotBlank(xml)) {
	            StringReader srReader = new StringReader(xml);
	            InputSource source = new InputSource(srReader);
	            Document superInfo = builder.build(source);
	            Element infoEle = superInfo.getRootElement();
	//			Namespace nss = new Namespace(namespace, "");
	            value = infoEle.getTextNormalize();//infoEle.getAttributeValue("string", namespace);//.getChildTextNormalize("string");// infoEle.getChildText("content");//.getAttributeValue("content");   ,namespace
        	}else {
        		LOG.info("XML为空。");
        		return "";
        	}
    	} catch (JDOMException e) {
        		LOG.error(e.getMessage());
        } catch (IOException e) {
        	LOG.error(e.getMessage());
        }
        return value;
    }
}
